import org.apache.hadoop.hive.ql.exec.UDF;

import java.io.UnsupportedEncodingException;

/**
 * 字符串校验
 * 全角转半角
 * 去特殊符号如/n,/r,/t
 */
public class ConvertStringUDF extends UDF {

    public static String evaluate(String str) throws UnsupportedEncodingException {
        if(str==null || "".equals(str)){
            return "999";
        }
        //全角转半角
        String s = full2HalfChange(str);
        //去特殊字符
        String strs = s.replaceAll("[\r|\n|\t]+", "");
        return strs;
    }


  /*全角转半角的 转换函数*/

    public static  String full2HalfChange(String QJstr)
            throws UnsupportedEncodingException {

        StringBuffer outStrBuf = new StringBuffer("");

        String Tstr = "";

        byte[] b = null;

        for (int i = 0; i < QJstr.length(); i++) {
            Tstr = QJstr.substring(i, i + 1);
            // 全角空格转换成半角空格
            if (Tstr.equals("　")) {
                outStrBuf.append(" ");
                continue;
            }

            b = Tstr.getBytes("unicode");
            // 得到 unicode 字节数据
            if (b[2] == -1) {
                // 表示全角？
                b[3] = (byte) (b[3] + 32);
                b[2] = 0;
                outStrBuf.append(new String(b, "unicode"));
            } else {
                outStrBuf.append(Tstr);
            }
        } // end for.
        return outStrBuf.toString();
    }

    /*半角转全角*/

    public static final String half2Fullchange(String QJstr)
            throws UnsupportedEncodingException {
        StringBuffer outStrBuf = new StringBuffer("");
        String Tstr = "";
        byte[] b = null;
        for (int i = 0; i < QJstr.length(); i++) {
            Tstr = QJstr.substring(i, i + 1);
            if (Tstr.equals(" ")) {
                // 半角空格
                outStrBuf.append(Tstr);
                continue;
            }
            b = Tstr.getBytes("unicode");
            if (b[2] == 0) {
                // 半角?
                b[3] = (byte) (b[3] - 32);
                b[2] = -1;
                outStrBuf.append(new String(b, "unicode"));
            } else {
                outStrBuf.append(Tstr);
            }
        }
        return outStrBuf.toString();
    }


}